const express = require('express')
const user = require('../db/userSchema_mobile')
const article = require('../db/articleSchema')
const social = require('../db/socialSchema_mobile')
const userPC = require('../db/userSchema')
const doctor = require('../db/doctorSchema')
const router = express.Router()

// 获取全部移动端用户信息
router.get('/getAllUserMoble', async (req, res) => {
	const userobj = await user.find({})
	if (userobj) {
        const arr = userobj.map(i => {
            return {
                id: i.id,
                name: i.userName,
                phone: i.phone,
                img: i.userImg,
                sex: i.sex,
                addTime: i.addTime,
                flag: i.flag
            }
        })
        const userNum = arr.length
        let nan = 0
        let nv = 0
        arr.forEach(i => {
            if (i.sex === '男') {
                nan += 1
            } else if (i.sex === '女') {
                nv += 1
            }
        })
		res.send({
			status: 200,
			data: {
				code: 0,
                userNum,
                nan,
                nv,
				userobj: arr
			},
			msg: '查询成功'
		})
	} else {
		res.send({
			status: 500,
			msg: '查询失败'
		})
	}
})

// 获取全部医师信息
router.get('/getAllDoctors', async (req, res) => {
	const doctorobj = await doctor.find({})
	if (doctorobj) {
        const arr = doctorobj.map(i => {
            return {
                id: i.id,
                name: i.userName,
                phone: i.phone,
                department: i.department,
                sex: i.sex,
                unit: i.unit,
                strengths: i.strengths,
                title: i.title
            }
        })
        const sum = arr.length
        let nei = 0
        let zhong = 0
        let ying = 0
        let xin = 0
        let quan = 0
        arr.forEach(i => {
            if (i.department === '内科') {
                nei += 1
            } else if (i.department === '中医科') {
                zhong += 1
            } else if (i.department === '营养科') {
                ying += 1
            } else if (i.department === '心理科') {
                xin += 1
            } else if (i.department === '全科') {
                quan += 1
            }
        })
		res.send({
			status: 200,
			data: {
				code: 0,
                sum,
                nei,
                zhong,
                ying,
                xin,
                quan,
				userobj: arr
			},
			msg: '查询成功'
		})
	} else {
		res.send({
			status: 500,
			msg: '查询失败'
		})
	}
})

// 获取10日内平台用户增长数据
router.post('/getSystemUsersData', (req, res) => {
    // const { time } = req.body
    // const obj = {}
    // time.forEach(e => {
    //     obj[e] = 0
    // })

    const time = []
    for(let i = 0; i < 10; i ++) {
        time.push(getBeforeDayTime(i))
    }
    const obj = {}
    time.forEach(e => {
        obj[e] = 0
    })
    const {startTime, endTime} = req.body
    user.find({ $and: [ {addTime: {$gt: startTime}}, {addTime: {$lt: endTime}} ] }).then(result => {
        if (result) {
            for (const key of Object.keys(obj)) {
                for (const i of result) {
                    if (key == i.addTime.split(' ')[0]) {
                        obj[key] += 1
                    }
                }
            }
            res.send({
                status: 200,
                data: {
                    code: 0,
                    obj
                },
                msg: '查询成功'
            })
        } else {
            res.send({
                status: 500,
                msg: '查询错误'
            })
        }
    })
    // user.find({ addTime: { $in: time } }).then(result => {
    //     if (result) {
    //         console.log(result)
    //         for (const key of Object.keys(obj)) {
    //             for (const i of result) {
    //                 if (key === i.addTime) {
    //                     obj[key] += 1
    //                 }
    //             }
    //         }
    //         res.send({
    //             status: 200,
    //             data: {
    //                 code: 0,
    //                 obj
    //             },
    //             msg: '查询成功'
    //         })
    //     } else {
    //         res.send({
    //             status: 500,
    //             msg: '查询错误'
    //         })
    //     }
    // })
})

// 获取平台文章来源统计
router.get('/getSystemArticleSource', (req, res) => {
    const articleObj = {}
    article.find({}).then(result => {
        if (result) {
            result.forEach(e => {
                articleObj[e.author] = 0
            })
            for (const key of Object.keys(articleObj)) {
                for (const i of result) {
                    if (key === i.author) {
                        articleObj[key] += 1
                    }
                }
            }
            res.send({
                status: 200,
                data: {
                    code: 0,
                    obj: articleObj
                },
                msg: '查询成功'
            })
        } else {
            res.send({
                status: 500,
                msg: '查询错误'
            })
        }
    })
})

// 获取用户动态，并处理，返回前五位发动态最多的用户
router.get('/getuserDynamicSort', (req, res) => {
    const dynamicObj = {}
    social.find({}).then(result => {
        if (result) {
            /*
                1, 拿到对应数据对象
                { '王二狗': 3, '大狗': 2, '小狗': 1 }
            */
            result.forEach(e => {
                dynamicObj[e.userName] = 0
            })
            for (const key of Object.keys(dynamicObj)) {
                for (const i of result) {
                    if (key === i.userName) {
                        dynamicObj[key] += 1
                    }
                }
            }
            /*
                2, 转成数组结构并按value排序
                [
                    { key: '小狗', value: 1 },
                    { key: '大狗', value: 2 },
                    { key: '王二狗', value: 3 }
                ]
            */
            const newArr = []
            for (const [key, value] of Object.entries(dynamicObj)) {
                newArr.push({key, value})
            }
            /*
                3, 排序并获取前五名
            */
            let sortData = function (data){
                return data.sort((a,b) => {
                    return b.value - a.value
                })
            }
            const a = sortData(newArr).splice(0, 5)
            // 添加用户头像
            for (const item of result) {
                a.forEach(obj => {
                    if (item.userName === obj.key) {
                        obj.userImg = item.userImg
                    }
                })
            }
            res.send({
                status: 200,
                data: {
                    code: 0,
                    arr: a
                },
                msg: '查询成功'
            })
        } else {
            res.send({
                status: 500,
                msg: '查询错误'
            })
        }
    })
})

// 修改密码
router.post('/editPassword', (req, res) => {
	const {userName, password0, password1} = req.body
	userPC.findOne({userName}).exec(function(err,data){
		// 先查询到指定的数据data
		// 然后修改数据
		if (data) {
            if (data.password !== password0) {
                res.send({
                    status: 500,
					msg: '原密码错误'
                })
                return
            }
			data.save(function(err){
                data.password = password1
				// err在修改错误时报错有值
				if (err) {
					res.send({
						status: 500,
						msg: '修改失败'
					})
				} else {
					res.send({
						status: 200,
						data: {
							code: 0,
						},
						msg: '修改成功'
					})
				}
			})
		}	
	})
})


module.exports = router
